/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller.member;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.entity.Vip;
import com.rzico.basics.model.MapPoint;
import com.rzico.basics.model.ShopVo;
import com.rzico.basics.service.*;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysPvuvTravel;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 会员控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "会员接口")
@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CouponCodeService couponCodeService;

    @Autowired @Lazy
    private EnterpriseService enterpriseService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private ShopService shopService;

    @Autowired
    private MsgService msgService;

    @Autowired
    private VipService vipService;

    /**
     * 查询我推广的会员
     *
     * @return
     */
    @ApiOperation("查询我推广的会员")
    @GetMapping("/memberList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "状态(0.未成交,1.已成交)", dataType = "String", paramType = "query")
    })
    public CommResult<Member> memberList(Integer status, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        Member member = memberService.getCurrent();
        params.put("promoterId", member.getId());

        if (status!=null) {
            params.put("status",status);
        }



        params.put("deleted", false);

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Member> list = memberService.selectList(params);
        PageResult<Member> pageResult = new PageResult<Member>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }


    @ApiOperation("获取登录会员信息")
    @GetMapping(value = "/getInfo")
    public CommResult<Member> getInfo(HttpServletRequest request) {
        CommResult commResult = new CommResult();
        Member member = memberService.getCurrent();
        Map<String, Object> data = new HashMap<>();
        if (member!=null) {
            data.put("member",member);
        }

        data.put("freezeBalance",member.getFreezeBalance());
        data.put("balance",member.getBalance());
        data.put("point",member.getPoint());
        data.put("matchPoint",member.getMatchPoint());
        data.put("freezePoint",member.getFreezePoint());

        //获取提货券
        Map<String,Object> params = new HashMap<>();
        params.put("memberId",member.getId());
        params.put("deleted",false);
        params.put("isUsed",false);
        params.put("type",3);
        params.put("vaildDate",new Date());
        data.put("couponCode",couponCodeService.selectSumCount(params));


        //获取水票

        params.clear();
        params.put("memberId",member.getId());
        params.put("type",3);
        data.put("virtualStock",couponCodeService.selectVirtualCount(params));


        params.clear();
        params.put("enterpriseId",member.getEnterpriseId());
        List<Vip> vipList = vipService.selectList(params);

        Vip vip = null;
        for (Vip v:vipList) {
            if (v.getVipType().equals(3)) {
                vip = v;
            }
        }

        data.put("vip",vip);

        commResult.setData(data);
        return commResult;
    }


    /**
     * 查询单条会员
     *
     * @return
    */
    @ApiOperation("查询单条会员")
    @GetMapping("/find/{id}")
    public CommResult<Member> find(@PathVariable String id) {
        Member result = memberService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("member",result);
        return CommResult.success(result);

    }


    /**
     * 获取推送人商户信息
     *
     * @return
     */
    @ApiOperation("获取推送人商户信息")
    @GetMapping("/XUIDLocation")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "xuid", value = "推荐人USERID", dataType = "String", paramType = "query")
    })
    public CommResult<Member> XUIDLocation(String isvId,String xuid) {

        SysUser sysUser = sysUserService.selectByPrimaryKey(xuid);
        if (sysUser == null) {
            return CommResult.error("无效推荐ID");
        }

        SysMch sysMch = null;

        // 1.商家账号
        if (sysUser.getUserType().equals(1)) {
            sysMch = sysMchService.findById(sysUser.getMchId());
        } else {
            Member member = memberService.findByUserId(sysUser.getId());
            Enterprise enterprise = enterpriseService.findById(member.getEnterpriseId());
            sysMch = sysMchService.findById(enterprise.getMchId());
        }

        Map<String,Object> data = new HashMap<>();
        data.put("sysMch",sysMch);

        return CommResult.success(data);

    }

    /**
     * 锁定用户关系
     *
     * @return
     */

    @Log(desc = "锁定用户关系", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("锁定用户关系")
    @PostMapping("/lockSysUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mchId", value = "ISV商户号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "xuid", value = "推荐人USERID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "shopId", value = "店铺ID", dataType = "String", paramType = "query")
    })
    public CommResult<Member> lockSysUser(String mchId,String xuid,Long shopId) {

        Member member = memberService.getCurrent();
        Member prometer = null;
        if (xuid!=null) {
            prometer = memberService.findByUserId(xuid);
        }
        if (member!=null && member.getAmount().compareTo(BigDecimal.ZERO)==0 && member.getVip()==0) {

            //没有产生消费记录时，如果是总店的客户，可以被特约商户绑定
            if (mchId!=null) {
                //判断是否总店会员

                    if (member.getShopId()==null && shopId!=null) {
                        Shop shop = shopService.selectByPrimaryKey(shopId);
                        member.setEnterpriseId(shop.getEnterpriseId());
                        if (shopId!=null) {
                            member.setShopId(shopId);
                        }
                        memberService.updateByPrimaryKeySelective(member);

                        Map<String, Object> content = new HashMap<>();
                        content.put("title", "新会员通知");
                        if (prometer!=null) {
                            content.put("content", prometer.getName() + "推荐" + member.getName().concat("成为新会员"));
                            msgService.sendNotity(member, "msg-notify", prometer.getName() + "推荐" + member.getName().concat("成为新会员"), JSON.toJSONString(content),null);
                        } else {
                            content.put("content",member.getName().concat("注册成为新会员"));
                            msgService.sendNotity(member, "msg-notify", member.getName().concat("注册成为新会员"), JSON.toJSONString(content),null);
                        }
                    }

            }

            if (prometer!=null && !prometer.getId().equals(member.getId())) {
                member.setPromoterId(prometer.getId());
                memberService.updateByPrimaryKeySelective(member);
            }

            return CommResult.success("锁定会员成功");
        } else {
            return CommResult.success("已绑定会员");
        }

    }


    /**
     * 获取我的二维码
     * @return
     */
    @ApiOperation("获取我的二维码")
    @GetMapping("/createQrcode")
    public CommResult<String> qrcode() {

        Member member = memberService.getCurrent();

        if (member==null) {
            return CommResult.error("绑定会员");
        }

        Enterprise enterprise = enterpriseService.selectByPrimaryKey(member.getEnterpriseId());
        if (enterprise.getDomain()==null) {
            SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
            if (sysMch.getMchType().equals(2) || sysMch.getMchType().equals(1)) {
                enterprise = enterpriseService.findByMch(sysMch.getIsvId());
            }
        }
        String domain = enterprise.getDomain();
        if (domain==null) {
            domain = "http://g"+enterprise.getMchId()+".rzico.com";
        }

        String qrcodeData = domain+"/q/"+member.getUserId();

        return CommResult.success(qrcodeData);
    }


}
